//
//  LFSpectrumTrimmerGridView.m
//  LFMediaEditingController
//
//  Created by LamTsanFeng on 2017/7/18.
//  Copyright © 2017年 LamTsanFeng. All rights reserved.
//

#import "LFSpectrumTrimmerGridView.h"
#import "LFResizeControl.h"
#import "LFVideoTrimmerGridLayer.h"
#import "LFGridMaskLayer.h"
#import "UIView+LFMEFrame.h"


@interface LFResizeSpectrumImageControl : LFResizeControl

@end

@implementation LFResizeSpectrumImageControl

//type 1左边 2右边
- (instancetype)initCustom:(CGRect)frame type:(NSInteger)type
{
    self = [super initWithFrame:frame];
    if (self) {
        if (type == 2) {
            UIImageView *dot = [[UIImageView alloc] initWithFrame:CGRectMake((frame.size.width - 40)/2.0, frame.size.height - 36, 40, 40)];
            dot.image = [UIImage imageNamed:@"edit_dot"];
            [self addSubview:dot];
        } else {
            UIImageView *dot = [[UIImageView alloc] initWithFrame:CGRectMake((frame.size.width - 40)/2.0, -4, 40, 40)];
            dot.image = [UIImage imageNamed:@"edit_dot"];
            [self addSubview:dot];
        }
        
    }
    return self;
}

@end


/** 可控范围 */
const CGFloat kSpectrumTrimmerGridControlWidth = 55.f;
const CGFloat kSpectrumTrimmerGridLayerLineWidth = 2.f;

@interface LFSpectrumTrimmerGridView () <lf_resizeConrolDelegate>

@property (nonatomic, weak) LFResizeSpectrumImageControl *leftCornerView;
@property (nonatomic, weak) LFResizeSpectrumImageControl *rightCornerView;

@property (nonatomic, weak) LFResizeControl *centerCornerView;

/** 边框 */
@property (nonatomic, weak) LFVideoTrimmerGridLayer *gridLayer;
/** 背景 */
@property (nonatomic, weak) LFVideoTrimmerGridLayer *bg_gridLayer;
/** 遮罩 */
@property (nonatomic, weak) LFGridMaskLayer *gridMaskLayer;

@property (nonatomic, assign) CGRect initialRect;

@end

@implementation LFSpectrumTrimmerGridView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self customInit];
    }
    return self;
}

- (void)customInit{
    
    /** 背景 */
    LFVideoTrimmerGridLayer *bg_gridLayer = [[LFVideoTrimmerGridLayer alloc] init];
    bg_gridLayer.frame = self.bounds;
    bg_gridLayer.lineWidth = kSpectrumTrimmerGridLayerLineWidth;
    bg_gridLayer.bgColor = [UIColor clearColor];
    bg_gridLayer.gridColor = [UIColor colorWithWhite:1.f alpha:0.5f];
    bg_gridLayer.gridRect = self.bounds;
    bg_gridLayer.hidden = YES;
    [self.layer addSublayer:bg_gridLayer];
    self.bg_gridLayer = bg_gridLayer;
    
    /** 遮罩 */
    LFGridMaskLayer *gridMaskLayer = [[LFGridMaskLayer alloc] init];
    gridMaskLayer.frame = self.bounds;
    gridMaskLayer.maskColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:gridMaskLayer];
    self.gridMaskLayer = gridMaskLayer;
    
    /** 边框 */
    LFVideoTrimmerGridLayer *gridLayer = [[LFVideoTrimmerGridLayer alloc] init];
    gridLayer.frame = self.bounds;
    gridLayer.lineWidth = kSpectrumTrimmerGridLayerLineWidth;
    gridLayer.bgColor = rgba(236, 94, 101, 0.3);
    gridLayer.gridColor = rgba(236, 94, 101, 1);
    [self.layer addSublayer:gridLayer];
    self.gridLayer = gridLayer;
    
    /** 左右控制器 */
    self.leftCornerView = [self createResizeLeftControl];
    self.rightCornerView = [self createResizeRightControl];
    self.centerCornerView = [self createCenterResizeControl];
    
    self.gridRect = self.bounds;
    self.controlMinWidth = self.frame.size.width * 0.20f;
    self.controlMaxWidth = self.frame.size.width;
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.gridLayer.frame = self.bounds;
    self.bg_gridLayer.frame = self.bounds;
    self.gridMaskLayer.frame = self.bounds;
    
    CGRect rect = self.gridRect;
    
    self.leftCornerView.frame = (CGRect){CGRectGetMinX(rect) - CGRectGetWidth(self.leftCornerView.bounds) / 2, (CGRectGetHeight(rect) - CGRectGetHeight(self.leftCornerView.bounds)) / 2, self.leftCornerView.bounds.size};
    self.rightCornerView.frame = (CGRect){CGRectGetMaxX(rect) - CGRectGetWidth(self.rightCornerView.bounds) / 2, (CGRectGetHeight(rect) - CGRectGetHeight(self.rightCornerView.bounds)) / 2, self.rightCornerView.bounds.size};
    
    self.centerCornerView.frame = CGRectMake(CGRectGetMaxX(self.leftCornerView.frame), CGRectGetMinY(self.leftCornerView.frame), CGRectGetMinX(self.rightCornerView.frame)-CGRectGetMaxX(self.leftCornerView.frame), CGRectGetHeight(self.leftCornerView.frame));
}

- (BOOL)isEnabledLeftCorner
{
    return self.leftCornerView.userInteractionEnabled;
}

- (void)setEnabledLeftCorner:(BOOL)enabledLeftCorner
{
    self.leftCornerView.userInteractionEnabled = enabledLeftCorner;
}

- (BOOL)isEnabledRightCorner
{
    return self.rightCornerView.userInteractionEnabled;
}

- (void)setEnabledRightCorner:(BOOL)enabledRightCorner
{
    self.rightCornerView.userInteractionEnabled = enabledRightCorner;
}

- (void)setProgress:(double)progress
{
    if (isnan(progress) || progress < 0) {
        return;
    }
    _progress = progress;
//    _slider.lfme_x = progress*self.lfme_width;
}

- (void)setHiddenProgress:(BOOL)hidden
{
//    _slider.hidden = hidden;
}

#pragma mark - lf_resizeConrolDelegate

- (void)lf_resizeConrolDidBeginResizing:(LFResizeControl *)resizeConrol
{
    [self bringSubviewToFront:resizeConrol];
    
    self.bg_gridLayer.hidden = NO;
    self.initialRect = self.gridRect;
    
    if ([self.delegate respondsToSelector:@selector(lf_spectrumTrimmerGridViewDidBeginResizing:)]) {
        [self.delegate lf_spectrumTrimmerGridViewDidBeginResizing:self];
    }
}

- (void)lf_resizeConrolDidResizing:(LFResizeControl *)resizeConrol
{
    CGRect gridRect = [self cropRectMakeWithResizeControlView:resizeConrol];
    
    if (!CGRectEqualToRect(_gridRect, gridRect)) {
        [self setGridRect:gridRect animated:NO];
        if ([self.delegate respondsToSelector:@selector(lf_spectrumTrimmerGridViewDidResizing:)]) {
            [self.delegate lf_spectrumTrimmerGridViewDidResizing:self];
        }
    }
}

- (void)lf_resizeConrolDidEndResizing:(LFResizeControl *)resizeConrol
{
    self.bg_gridLayer.hidden = YES;
    self.leftCornerView.enabled = YES;
    self.rightCornerView.enabled = YES;
    self.centerCornerView.enabled = YES;
    if ([self.delegate respondsToSelector:@selector(lf_spectrumTrimmerGridViewDidEndResizing:)]) {
        [self.delegate lf_spectrumTrimmerGridViewDidEndResizing:self];
    }
}

- (void)setGridRect:(CGRect)gridRect
{
    [self setGridRect:gridRect animated:NO];
}

- (void)setGridRect:(CGRect)gridRect animated:(BOOL)animated
{
    if (!CGRectEqualToRect(_gridRect, gridRect)) {
        _gridRect = gridRect;
        [self.gridLayer setGridRect:gridRect animated:animated];
        self.gridMaskLayer.maskRect = self.gridRect;
        [self setNeedsLayout];
    }
}

#pragma mark - private
- (LFResizeSpectrumImageControl *)createResizeLeftControl {
    LFResizeSpectrumImageControl *control = [[LFResizeSpectrumImageControl alloc] initCustom:(CGRect){CGPointMake(0, -kSpectrumTrimmerGridLayerLineWidth/2), CGSizeMake(kSpectrumTrimmerGridControlWidth, self.bounds.size.height+kSpectrumTrimmerGridLayerLineWidth)} type:1];
    control.delegate = self;
    [self addSubview:control];
    return control;
}

- (LFResizeSpectrumImageControl *)createResizeRightControl {
    LFResizeSpectrumImageControl *control = [[LFResizeSpectrumImageControl alloc] initCustom:(CGRect){CGPointMake(0, -kSpectrumTrimmerGridLayerLineWidth/2), CGSizeMake(kSpectrumTrimmerGridControlWidth, self.bounds.size.height+kSpectrumTrimmerGridLayerLineWidth)} type:2];
    control.delegate = self;
    [self addSubview:control];
    return control;
}

- (LFResizeControl *)createCenterResizeControl {
    LFResizeControl *control = [[LFResizeControl alloc] initWithFrame:self.bounds];
    control.delegate = self;
    control.backgroundColor = [UIColor clearColor];
    [self addSubview:control];
    return control;
}

- (CGRect)cropRectMakeWithResizeControlView:(LFResizeControl *)resizeControlView {
    CGRect rect = self.gridRect;
    
    
    if (resizeControlView == self.leftCornerView) {
        rect = CGRectMake(CGRectGetMinX(self.initialRect) + resizeControlView.translation.x,
                          CGRectGetMinY(self.initialRect),
                          CGRectGetWidth(self.initialRect) - resizeControlView.translation.x,
                          CGRectGetHeight(self.initialRect));
    } else if (resizeControlView == self.rightCornerView) {
        rect = CGRectMake(CGRectGetMinX(self.initialRect),
                          CGRectGetMinY(self.initialRect),
                          CGRectGetWidth(self.initialRect) + resizeControlView.translation.x,
                          CGRectGetHeight(self.initialRect));
    } else if (resizeControlView == self.centerCornerView) {
        rect = CGRectMake(CGRectGetMinX(self.initialRect) + resizeControlView.translation.x,
                          CGRectGetMinY(self.initialRect),
                          CGRectGetWidth(self.initialRect),
                          CGRectGetHeight(self.initialRect));
    }
    /** ps：
     此处判断 不能使用CGRectGet开头的方法，计算会有问题；
     当rect = (origin = (x = 50, y = 618), size = (width = 61, height = -488)) 时，
     CGRectGetMaxY(rect) = 618；CGRectGetHeight(rect) = 488
     */
    
    if (resizeControlView == self.leftCornerView) {
        /** 限制宽度 超出 最大限度 */
        if (rect.size.width > self.controlMaxWidth || rect.origin.x < 0) {
            if (rect.size.width > self.controlMaxWidth) {
                CGFloat diff = (self.controlMaxWidth - rect.size.width);
                rect.origin.x -= diff;
                rect.size.width += diff;
            } else {
                rect.origin.x = 0;
            }
        } else
        /** 限制宽度 超出 最小限度 */
        if (rect.size.width < self.controlMinWidth) {
            CGFloat diff = self.controlMinWidth - rect.size.width;
            rect.origin.x -= diff;
            rect.size.width += diff;
            /** 最小值大于自身宽度 */
            if (rect.origin.x < 0) {
                rect.size.width += rect.origin.x;
                rect.origin.x = 0;
            }
        }
    } else if (resizeControlView == self.rightCornerView) {
        /** 限制宽度 超出 最大限度 */
        if (rect.size.width > self.controlMaxWidth || rect.origin.x+rect.size.width > self.frame.size.width) {
            CGFloat diff = rect.size.width > self.controlMaxWidth ? (self.controlMaxWidth - rect.size.width) : (self.frame.size.width-(rect.origin.x+rect.size.width));
            rect.size.width += diff;
        } else
        /** 限制宽度 超出 最小限度 */
        if (rect.size.width < self.controlMinWidth) {
            CGFloat diff = self.controlMinWidth - rect.size.width;
            rect.size.width += diff;
            /** 最小值大于自身宽度 */
            if (rect.origin.x+rect.size.width > self.frame.size.width) {
                rect.size.width = self.frame.size.width - rect.origin.x;
            }
        }
    } else if (resizeControlView == self.centerCornerView) {
        if (rect.origin.x < 0.f){
            rect.origin.x = 0.f;
        } else if ((rect.origin.x+rect.size.width) > self.frame.size.width) {
            rect.origin.x = self.frame.size.width - rect.size.width;
        }
    }
    return rect;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *view = [super hitTest:point withEvent:event];
//    if (self.leftCornerView == view) {
//        self.rightCornerView.enabled = NO;
//        self.centerCornerView.enabled = NO;
//    } else if (self.rightCornerView == view) {
//        self.leftCornerView.enabled = NO;
//        self.centerCornerView.enabled = NO;
//    } else if (self.centerCornerView == view) {
//        self.leftCornerView.enabled = NO;
//        self.rightCornerView.enabled = NO;
//    }
    return view;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event
{
    BOOL isHit = [super pointInside:point withEvent:event];
    
    if (!isHit) {
        return (CGRectContainsPoint(self.leftCornerView.frame, point) || CGRectContainsPoint(self.rightCornerView.frame, point)) || CGRectContainsPoint(self.centerCornerView.frame, point);
    }
    
    return isHit;
}
@end
